/**
 * Created by JetBrains PhpStorm.
 * User: valera
 * Date: 8/14/11
 * Time: 6:06 PM
 */
(function() {
    var url = '/product/search';
    var config = {};
    var events_ns = $.namespace('core.events.SearchTable');
    var item;
    var that;
    var isEmpty = function(ob){
        for(var i in ob){ if(ob.hasOwnProperty(i)){return false;}}
        return true;
    }
    var SearchTable = function() {
        that = this;

        window.c = my_clear = function(data) {
            for(var i in data) {
                if(data.hasOwnProperty(i)) {
                    if(typeof(data[i]) === 'object' && data[i] !== null) {
                        data[i] = my_clear(data[i]);
                        if(isEmpty(data[i])) {
                            delete(data[i]);
                        }
                    }
                    if(data[i] === null) {
                        delete(data[i]);
                    }
                }
            }
            return data;
        };

        $(events_ns).bind('load-data', function(_event_, is_external) {
            $.ajax({
                is_external: is_external,
                type: 'get',
                url: url,
                data: config,
                dataType: 'json',
                success: function(data) {
                    $(events_ns).triggerHandler('display', [data, this.is_external]);
                }
            });
        });
        $(events_ns).bind('display', function(_event_, data) {
            $(that.node).empty();
            if (data.items.length !== 0) {
                $.each(data.items, function() {
                    var new_item = item.clone();
                    $('.item-name-port', new_item).html(this.title);
                    $('.item-id-port', new_item).html('#' + this.id);
                    $('.item-price-port', new_item).html(this.price + '$');
                    $(that.node).append(new_item);
                });
            }
        });
        $(core.events).bind('page-load', function() {
            item = $($('#product-item-sample').html());
            that.node = $('#items-wrapper')[0];
        });
        $($.namespace('core.events.Address')).bind('internal-change', function(e, _event_) {
            config = $.unparam(_event_.value.substring(1));
            $(events_ns).triggerHandler('load-data');
        }).bind('external-change', function(e, _event_) {
            config = $.unparam(_event_.value.substring(1));
            $(events_ns).triggerHandler('load-data', [true]);
        })
        $(events_ns).bind('set-config', function(_event_, data, merge) {
            if (merge && data) {
                config = $.extend(true, config, data);
            } else {
                config = data;
            }
            my_clear(config);
            $.address.value($.param(config));
        });
    };

    $.namespace('core').SearchTable = new SearchTable();
})();

(function() {
    var total = 0;
    var current = 1;
    var ipp = 10;
    var page_count = 0;
    var events_ns = $.namespace('core.events.Navigation');
    var next_button, prev_button;
    var Navigation = function() {
        $(events_ns).bind('redraw', function() {
            $('.current-page').text(current);
            $('.total-page-count').text(page_count);
        });
        $(events_ns).bind('next-page', function() {
            if ((current + 1) <= page_count) {
                current++;
            } else {
                return false;
            }
            $(core.events.SearchTable).triggerHandler('set-config', [
                {page: current},
                true
            ]);
        });
        $(events_ns).bind('prev-page', function() {
            if ((current - 1) > 0) {
                current--;
            } else {
                return false;
            }
            $(core.events.SearchTable).triggerHandler('set-config', [
                {page: current},
                true
            ]);
        });
        $(core.events.SearchTable).bind('display', function(_event_, data) {
            total = parseInt(data.total);
            page_count = Math.ceil(total / ipp);
            current = parseInt(data.page);
            if (current == 1) {
                prev_button.addClass('disabled');
            } else {
                prev_button.removeClass('disabled');
                next_button.removeClass('disabled');
                if (current == page_count) {
                    next_button.addClass('disabled');
                }
            }
            $(events_ns).triggerHandler('redraw');
        });
        $(core.events).bind('page-load', function() {
            (next_button = $('.next-button')).click(function() {
                $(events_ns).triggerHandler('next-page');
            });
            (prev_button = $('.prev-button')).click(function() {
                $(events_ns).triggerHandler('prev-page');
            });
        });
    };
    window.core.Navigation = new Navigation();
})();

(function() {
    var def_opt = {
        delay: 300,
        callback: function() {
        }
    };
    var call_stack = [];
    jQuery.fn.quickSearch = function(options) {
        var that = this;
        options = $.extend(def_opt, options);
        $(this).defaultText();
        $(this).bind('quick-search', function() {
            options.callback.call(this, $(this).val(), options);
        });
        $(this).bind('keypress', function() {
            call_stack.push(true);
            setTimeout(function(node) {
                call_stack.pop();
                if (call_stack.length === 0) {
                    $(node).triggerHandler('quick-search');
                }
            }, options.delay, this);
        });
        $($.namespace('core.events.Address')).bind('external-change', function(e, _event_) {
            $(that).val(($.unparam(_event_.value.substring(1)))['search']);
        });
    };
})();

(function($) {
    var active;
    $.widget('ui.sort_switch', {
        _switch: function(node) {
            if(node.is_up === true) {
                node.is_up = false;
                $('.sort-value', node).html('down');
            } else {
                if(node.is_up === false || node.is_up === -1){
                    node.is_up = true;
                    $('.sort-value', node).html('up');
                }
            }

        },
        _prepare: function(data) {
            if(data.type != this.element.attr('data-type')) {
                this.element.addClass('inactive');
                this.element[0].is_up = -1;
                this.element.find('.sort-value').html('up');
                return;
            }
            active = this.element[0];
            var is_up = this.element[0].is_up = (data.order == 'asc');
            this.element.find('.sort-value').html(is_up ? 'up' : 'down');
            this.element.removeClass('inactive');
        },
        _create: function() {
            $.each(this.element, function() { this.is_up = -1; });
            $(this.element).bind('click', {ui:this}, function(e) {
                if(typeof(active) !== 'undefined') {
                    if(active !== this) {
                        $(active).addClass('inactive');
                        active.is_up = -1;
                        e.data.ui._switch(active);
                    }
                }
                $(this).removeClass('inactive');
                if(active === this || this.is_up === -1) {
                    e.data.ui._switch(this);
                }
                $($.namespace('core.events.SearchTable')).triggerHandler('set-config', [{sort: {type: $(this).attr('data-type'), order: this.is_up ? 'asc' : 'desc'}}, true]);
                active = this;
            });
            $($.namespace('core.events.SearchTable')).bind('display', {ui: this}, function(e, data, is_external) {
                if(!is_external) { return; }
                e.data.ui._prepare(data.sort);
            });
        }
    });
})(jQuery);